﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace iLangl.Transport.Communication
{
	public class BaseRobotOperation : IRobotOperation
	{
		public BaseRobotOperation(IRobot robot)
		{
			_robot = robot;
		}
		#region IRobotOperation Members

		protected IRobot _robot;
		public virtual IRobot Robot
		{
			get
			{
				return _robot;
			}
			set
			{
				_robot = value;
			}
		}

		#endregion

		protected void MoveTo(FileInfo file, String destinationFolder)
		{
			String moveToFile = Path.Combine(destinationFolder, file.Name);
			if (File.Exists(moveToFile))
			{
				file.Delete();
			}
			else
			{
				file.MoveTo(moveToFile);
			}
		}

		public virtual void Set(IRobotItem item)
		{
			if(!(item is IPackage))
				throw new ArgumentException("IPackage Item expected to sent!");

			IPackage package = item as IPackage;

			if (package.IsSynced())
			{
				throw new ApplicationException("Only async packages is going through this robot!");
			}
			else
			{

				FileInfo fileinfo = new FileInfo(package.DeliveryPackageFileName);

				try
				{
					execute(package, fileinfo);

					MoveTo(fileinfo, TransportConfiguration.Instance.DispatchedPackageFolder);
				}
				catch (System.Exception ex)
				{
					MoveTo(fileinfo, TransportConfiguration.Instance.CorruptedPackageFolder);
					throw ex;
				}

			}
		}

		protected virtual void execute(IPackage package, FileInfo fileinfo)
		{
		}
	}
}
